package v1

import (
	"errors"
	"gin-luban-server/global"
	"gin-luban-server/model/request"
	"gin-luban-server/model/response"
	"gin-luban-server/service"
	"gin-luban-server/utils"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"go.uber.org/zap"
	"net/http"
	"strconv"
)

// @Tags JumpServer
// @Summary 获取应用树JumpServerTree
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.Empty true "空"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /jump/server/getJumpServerTree [get]
//type WsConn struct {
//	*websocket.Conn
//	Mux sync.RWMutex
//}
func GetJumpServerTree(c *gin.Context) {
	var R request.JumpServerParams
	_ = c.ShouldBind(&R)
	if code,msg := utils.Validate(&R);code != response.SUCCESS_VALIDATE {
		response.FailValidateMessage(msg,c)
		return
	}
	if err, menus := service.GetJumpServerTree(R.UserName); err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
		response.FailWithMessage("获取失败", c)
	} else {
		response.OkWithDetailed(response.JumpServerMenusResponse{Menus: menus}, "获取成功!", c)
	}

}

var upgrader = websocket.Upgrader{
	ReadBufferSize:  10240,
	WriteBufferSize: 1024 * 1024 * 10,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func WebSshVirtualTerm(c *gin.Context) {
	ids  := c.DefaultQuery("Id", "")
	col := c.DefaultQuery("cols", "")
	row := c.DefaultQuery("rows", "")
	uuid := c.DefaultQuery("uuid", "")
	if  col == "" || row == "" || ids == "" || uuid== "" {
		err :=errors.New("参数为空")
		global.GVA_LOG.Error("连接失败!", zap.Any("err", err))
		response.FailWithMessage("连接失败" + err.Error(), c)
	}
	cols, _ := strconv.Atoi(col)
	rows, _ := strconv.Atoi(row)
	Id,_:=strconv.ParseFloat(c.DefaultQuery("Id", ""),64)
	sshClientInfo, err := service.GetLogicSshClient(Id,uuid)
	if err != nil {
		global.GVA_LOG.Error("连接失败!", zap.Any("err", err))
		response.FailWithMessage("连接失败" + err.Error(), c)
	}
	terminal := service.Terminal{
		Columns: uint32(cols),
		Rows:    uint32(rows),
	}
	wsConn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
		//response.FailWithMessage("连接失败！" + err.Error(), c)
	}
	client,err := service.GenerateClient(sshClientInfo)
	if err != nil {
		//response.FailWithMessage("连接失败" + err.Error(), c)
		defer wsConn.Close()
		return
	}
	client.RequestTerminal(terminal)
	go client.Connect(wsConn)
}




